package cn.laixueit.service.impl;

import cn.laixueit.mapper.StudentMapper;
import cn.laixueit.pojo.*;
import cn.laixueit.service.ClassesService;
import cn.laixueit.service.StudentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ClassesService classesService;

    @Override
    public List<Classes> findClassList() {
        List<Classes> classesList = classesService.findClassList();
        return classesList;
    }

    @Override
    public void save(Student student) {
        studentMapper.insertSelective(student);
    }

    @Override
    public PageInfo<Student> page(Integer start, Integer size, Student student) {
        PageHelper.startPage(start,size);
        List<Student> studentList = studentMapper.selectByExample(getExample(student));
        PageInfo<Student> pageInfo = new PageInfo<>(studentList);
        return pageInfo;
    }

    @Override
    public Student findById(Integer id) {
        return studentMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Classes> findAllClassList() {
        List<Classes> classList = classesService.findAllClassList();
        return classList;
    }

    @Override
    public void update(Student student) {
        studentMapper.updateByPrimaryKey(student);
    }

    @Override
    public Boolean removeById(Integer id) {
        try {
            studentMapper.deleteByPrimaryKey(id);
        }catch (Exception e) {
            return false;
        }
        return true;
    }

    private StudentExample getExample( Student student) {
        StudentExample example = new StudentExample();
        StudentExample.Criteria criteria = example.createCriteria();
        if(!StringUtils.isEmpty(student.getName())){
            criteria.andNameLike("%"+student.getName()+"%");
        }
        if(student.getGender() != null){
            criteria.andGenderEqualTo(student.getGender());
        }
        if(student.getClassid() != null){
            criteria.andClassidEqualTo(student.getClassid());
        }
        return example;
    }
}
